<?php

namespace app\admin\controller\booking;

use app\admin\model\booking\HouseForm;
use addons\booking\model\OrderCalendar;
use app\admin\library\Auth;

/**
 * 房间管理
 *
 * @icon fa fa-circle-o
 */
class House extends Base
{

    /**
     * House模型对象
     * @var \app\admin\model\booking\House
     */
    protected $model = null;
    protected $dataLimitField = 'store_id';
    protected $dataLimitFieldAutoFill = false;
    

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\booking\House;
        $this->view->assign("toShopPayList", $this->model->getToShopPayList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    protected function getDataLimitAdminIds()
    {
        $auth = Auth::instance();
        if ($this->addonsConfig['isStoreAllocate'] == 1 && !$auth->isSuperAdmin()) {
            return $this->authStoreIds;
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['Store', 'typeConfig', 'floorConfig', 'HouseForm'])
                ->where($where)
                ->alias('h')
                ->field('h.*,GROUP_CONCAT(c.name,"|",c.type) group_name')
                ->join('booking_config c', 'FIND_IN_SET(c.id,h.tag_config_ids) or FIND_IN_SET(c.id,h.facility_config_ids)', 'LEFT')
                ->order($sort, $order)
                ->group('h.id')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $fields = \app\admin\model\booking\Fields::where('source', 'house')->order("weigh DESC, id ASC")->select();
        $this->assignconfig('fields', $fields);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $fields = \app\admin\model\booking\Fields::where('source', 'house')->order("weigh DESC, id ASC")->select();
        $this->assign('fields', $fields);
        return parent::add();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $fields = \app\admin\model\booking\Fields::where('source', 'house')->order("weigh DESC, id ASC")->select();
        $formRow = HouseForm::where('house_id', $ids)->find();
        foreach ($fields as $item) {
            if ($formRow && isset($formRow[$item['name']])) {
                $item->value = $formRow[$item['name']];
            }
        }
        $this->assign('fields', $fields);
        return parent::edit($ids);
    }

    /**
     * 房间预订状态
     */
    public function search()
    {
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $param = $this->request->param();

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model->with(['Store'])
                ->field('h.id,h.store_id,h.market_price,h.tag_config_ids,h.price,h.name,h.room,h.area,h.livenums,h.status,h.images,h.createtime,GROUP_CONCAT(c.name) tag_names')
                ->where(function ($query) use ($param) {

                    $query->where('status', 'up');

                    if (isset($param['store_id']) && !empty($param['store_id'])) {
                        $query->where('store_id', $param['store_id']);
                    }
                    $time1 = strtotime(date('Y-m-d'));
                    $time2 = $time1 + 3600 * 24;
                    //按日期筛选房间【排除被预订的】
                    if (isset($param['calendar']) && !empty($param['calendar'])) {
                        $calendar = explode(' - ', $param['calendar']);
                        $time1 = strtotime($calendar[0]);
                        $time2 = $time1 + 3600 * 24;
                        if (count($calendar) == 2) { //时间范围
                            $time2 = strtotime($calendar[1]);
                        }
                    }
                    $data = OrderCalendar::field('house_id')->where('status', 'normal')->where('reserve_time', '>=', $time1)->where('reserve_time', '<', $time2)->group('house_id')->select();
                    $house_ids = [];
                    foreach ($data as $item) {
                        $house_ids[$item['house_id']] = $item['house_id'];
                    }
                    $query->where('h.id', 'not in', $house_ids);
                })->alias('h')
                ->join('booking_config c', 'FIND_IN_SET(c.id,h.tag_config_ids)', 'LEFT')
                ->where($where)
                ->order($sort, $order)
                ->group('h.id')
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
}
